#!/usr/bin/env python

import os
import sys
import re
import math
import optparse
from os.path import join as joinpath

optparser = optparse.OptionParser()

optparser.add_option('-c', '--confs', dest='confs',
                     default=' ',
                     help='Configurations to validate '
                     " (default: '%default')" )
 
(options,leftovers) = optparser.parse_args()

work_dir = 'spec_workdir'
isa = 'trips'
inputset = 'ref'
home = os.environ['HOME']

result_dir = os.path.join(home, work_dir, 'results', isa, 'linux',
                          inputset)

output_dir = os.path.join(home, work_dir, 'figs')

int_benchmarks = ['gzip','vpr','gcc','mcf',
                  'perlbmk',
                  'crafty','parser','gap','vortex',
                  'bzip2','twolf',]

float_benchmarks = ['wupwise','swim',
                    'mgrid','applu','mesa','art',
                    'equake','ammp','apsi'] 

all_benchmarks = int_benchmarks + float_benchmarks

key1 = 'Exiting'
key2 = '@'
key3 = 'tick'

panic_tick = 9223372036854775807

reference_conf = 'simple_fm_pb_pp_pmd_1024IQ_8b_hb_sp_3_2_Omax'
reference_stat = 'system.cpu.commit.COM:count'

class Stat(object):
    stat = float(0)
    def __init__(self,bname,sname,config,mode='normal',**kwargs):
        self.bname = bname
        self.sname = sname
        stats_file = result_dir + '/' + bname + '/' + config + '/'  +  'stats.txt'

        if not os.path.isfile(stats_file):
            self.stat = 0.0
            return

        if mode == 'normal':
            for line in open(stats_file):
                l = line.split()
                if not l:
                    continue
                l[0] = l[0].replace('system0','system')
                if l[0] == sname:
                    self.stat = float(l[1])
                    break
        elif mode == 'pdf':
            for line in open(stats_file):
                l = line.split()
                if not l:
                    continue
                l[0] = l[0].replace('system0','system')
                if l[0] == sname:
                    self.stat = (float(l[2].rstrip('%')) / 100.0)
                    break
        elif mode == 'cdf':
            for line in open(stats_file):
                l = line.split()
                if not l:
                    continue
                l[0] = l[0].replace('system0','system')
                if l[0] == sname:
                    self.stat = (float(l[3].rstrip('%')) / 100.0)
                    break
        else:
            sys.exit("Unknown mode while reading stats")

    
    def data(self):
        return self.stat

class Simout(object):
    stat = int(0)
    def __init__(self,bname,config,**kwargs):

        stats_file = result_dir + '/' + bname + '/' + config + '/' + \
                     'simout'

        if not os.path.isfile(stats_file):
            self.stat = 0.0
            return

        for line in open(stats_file):
            l = line.split()
            if not l:
                continue
            if l[0] == key1 and l[1] == key2 and l[2] == key3: 
                self.stat = int(l[3])
                break

    def data(self):
        return self.stat

if __name__ == '__main__':
    confs = (options.confs).split(',')
    configurations = []
    for conf in confs:
        if os.path.isdir(joinpath(home,'M5-EDGE','configs',\
                'trips_config',conf)):
            temp_confs = os.listdir(joinpath(home,'M5-EDGE',\
                'configs', 'trips_config',conf))
            configurations.extend([x for x in temp_confs])
        else:
            configurations.extend([conf])
    for j,conf in enumerate(configurations):

        conf = conf.split('.')[0]
        failed_bench_num = 0
        running_bench_num = 0
        failed_benches = []
        running_benches = []

        print '------------%s------------' % conf
        for i,bench in enumerate(all_benchmarks):
            print '----\t%s\t----' % bench
            ref_count = Stat(bench, reference_stat, reference_conf)
            out = Simout(bench, conf)
            print 'Sim_tick\t%d' % out.data()

            com_count = Stat(bench, reference_stat, conf)

            print 'Commit blocks\t%f -- Ref: %f' % (com_count.data(),
                    ref_count.data())

            if os.path.isfile(joinpath(result_dir, bench, conf,
                '.running')):
                running_benches.append(bench)
                running_bench_num += 1
            elif not os.path.isfile(joinpath(result_dir, bench, conf,
                'stats.txt')):
                print 'Waiting for running'
            else:
                if com_count.data() != ref_count.data() or \
                   out.data() == panic_tick or \
                   os.path.isfile(joinpath(result_dir, bench, conf,
                    '.error')):
                    print 'ERROR for %s' % bench
                    failed_benches.append(bench)
                    failed_bench_num += 1

        print '----------------'

        print 
        print '--------'
        print 'Running benchmarks: %d' % running_bench_num

        for r in running_benches:
            print '\t%s' % r

        print 'Failed benchmarks: %d' % failed_bench_num

        for r in failed_benches: 
            print '\t%s' % r

        print '--------'
        print
        print '----------------'

